import { RealSQLiteDatabase } from '../lib/real-sqlite-database';

/**
 * 检查当前数据库状态的脚本
 */
export class DatabaseStatusChecker {
  private db: RealSQLiteDatabase;

  constructor() {
    this.db = new RealSQLiteDatabase();
  }

  /**
   * 检查数据库状态
   */
  checkStatus(): void {
    console.log('=== 数据库状态检查 ===\n');
    
    try {
      // 1. 检查设备数据
      this.checkDevices();
      
      // 2. 检查参数数据
      this.checkParameters();
      
      // 3. 检查数据完整性
      this.checkDataIntegrity();
      
    } catch (error) {
      console.error('检查数据库状态时发生错误:', error);
    }
  }

  /**
   * 检查设备数据
   */
  private checkDevices(): void {
    console.log('📊 设备数据统计:');
    
    const devices = this.db.getAllDevices();
    console.log(`  总设备数: ${devices.length}`);
    
    if (devices.length > 0) {
      console.log(`  设备ID范围: ${Math.min(...devices.map(d => d.device_id))} - ${Math.max(...devices.map(d => d.device_id))}`);
      
      // 按专业统计
      const specialtyStats = devices.reduce((acc, device) => {
        acc[device.specialty] = (acc[device.specialty] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);
      
      console.log('  按专业分布:');
      Object.entries(specialtyStats).forEach(([specialty, count]) => {
        console.log(`    ${specialty}: ${count} 个设备`);
      });
      
      // 显示前5个设备示例
      console.log('\n  设备示例 (前5个):');
      devices.slice(0, 5).forEach(device => {
        console.log(`    ID:${device.device_id} - ${device.name} (${device.specialty})`);
        console.log(`      命名表: ${device.naming_table_id}`);
        console.log(`      位置表: ${device.position_table_id}`);
        console.log(`      基础参数表: ${device.base_params_table_id}`);
      });
    }
    
    console.log('');
  }

  /**
   * 检查参数数据
   */
  private checkParameters(): void {
    console.log('📋 参数数据统计:');
    
    const devices = this.db.getAllDevices();
    let totalNamingParams = 0;
    let totalPositionParams = 0;
    let totalBaseParams = 0;
    
    let devicesWithNaming = 0;
    let devicesWithPosition = 0;
    let devicesWithBase = 0;
    
    devices.forEach(device => {
      const namingParams = this.db.getNamingParametersByDeviceId(device.device_id);
      const positionParams = this.db.getPositionParametersByDeviceId(device.device_id);
      const baseParams = this.db.getBaseParametersByDeviceId(device.device_id);
      
      totalNamingParams += namingParams.length;
      totalPositionParams += positionParams.length;
      totalBaseParams += baseParams.length;
      
      if (namingParams.length > 0) devicesWithNaming++;
      if (positionParams.length > 0) devicesWithPosition++;
      if (baseParams.length > 0) devicesWithBase++;
    });
    
    console.log(`  命名参数总数: ${totalNamingParams}`);
    console.log(`    有命名参数的设备: ${devicesWithNaming}/${devices.length}`);
    
    console.log(`  位置参数总数: ${totalPositionParams}`);
    console.log(`    有位置参数的设备: ${devicesWithPosition}/${devices.length}`);
    
    console.log(`  基础参数总数: ${totalBaseParams}`);
    console.log(`    有基础参数的设备: ${devicesWithBase}/${devices.length}`);
    
    console.log('');
  }

  /**
   * 检查数据完整性
   */
  private checkDataIntegrity(): void {
    console.log('🔍 数据完整性检查:');
    
    const devices = this.db.getAllDevices();
    const issues = [];
    
    devices.forEach(device => {
      const namingParams = this.db.getNamingParametersByDeviceId(device.device_id);
      const positionParams = this.db.getPositionParametersByDeviceId(device.device_id);
      const baseParams = this.db.getBaseParametersByDeviceId(device.device_id);
      
      // 检查是否有设备缺少参数
      if (namingParams.length === 0 && device.naming_table_id) {
        issues.push(`设备 ${device.device_id} (${device.name}) 配置了命名表 ${device.naming_table_id} 但无命名参数`);
      }
      
      if (positionParams.length === 0 && device.position_table_id) {
        issues.push(`设备 ${device.device_id} (${device.name}) 配置了位置表 ${device.position_table_id} 但无位置参数`);
      }
      
      if (baseParams.length === 0 && device.base_params_table_id) {
        issues.push(`设备 ${device.device_id} (${device.name}) 配置了基础参数表 ${device.base_params_table_id} 但无基础参数`);
      }
    });
    
    if (issues.length === 0) {
      console.log('  ✅ 未发现数据完整性问题');
    } else {
      console.log(`  ⚠️  发现 ${issues.length} 个潜在问题:`);
      issues.slice(0, 10).forEach(issue => {
        console.log(`    - ${issue}`);
      });
      if (issues.length > 10) {
        console.log(`    ... 还有 ${issues.length - 10} 个问题`);
      }
    }
    
    console.log('');
  }

  /**
   * 获取详细的设备参数统计
   */
  getDetailedStats() {
    const devices = this.db.getAllDevices();
    const stats = {
      totalDevices: devices.length,
      devicesBySpecialty: {} as Record<string, number>,
      parameterStats: {
        naming: { total: 0, devicesWithData: 0 },
        position: { total: 0, devicesWithData: 0 },
        base: { total: 0, devicesWithData: 0 }
      },
      sampleDevices: [] as any[]
    };
    
    devices.forEach(device => {
      // 统计专业分布
      stats.devicesBySpecialty[device.specialty] = (stats.devicesBySpecialty[device.specialty] || 0) + 1;
      
      // 统计参数
      const namingParams = this.db.getNamingParametersByDeviceId(device.device_id);
      const positionParams = this.db.getPositionParametersByDeviceId(device.device_id);
      const baseParams = this.db.getBaseParametersByDeviceId(device.device_id);
      
      stats.parameterStats.naming.total += namingParams.length;
      stats.parameterStats.position.total += positionParams.length;
      stats.parameterStats.base.total += baseParams.length;
      
      if (namingParams.length > 0) stats.parameterStats.naming.devicesWithData++;
      if (positionParams.length > 0) stats.parameterStats.position.devicesWithData++;
      if (baseParams.length > 0) stats.parameterStats.base.devicesWithData++;
      
      // 收集样本设备
      if (stats.sampleDevices.length < 3) {
        stats.sampleDevices.push({
          device_id: device.device_id,
          name: device.name,
          specialty: device.specialty,
          parameterCounts: {
            naming: namingParams.length,
            position: positionParams.length,
            base: baseParams.length
          }
        });
      }
    });
    
    return stats;
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.db.close();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const checker = new DatabaseStatusChecker();
  
  try {
    checker.checkStatus();
    
    console.log('=== 详细统计信息 ===');
    const stats = checker.getDetailedStats();
    console.log(JSON.stringify(stats, null, 2));
    
  } catch (error) {
    console.error('执行检查时发生错误:', error);
  } finally {
    checker.cleanup();
  }
}
